package net;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.replay.ReplayingDecoder;

import system.Config;

enum MyDecoderState {
	   READ_LENGTH,
	   READ_CONTENT;
}

public class DataExtracter extends ReplayingDecoder<MyDecoderState> {
	
	   private int length;

	   public DataExtracter() {
		   // Set the initial state.
		   super(MyDecoderState.READ_LENGTH);
	   }
	   
	   @Override
	   protected Object decode(ChannelHandlerContext ctx,
			   Channel channel,
			   ChannelBuffer buf,
			   MyDecoderState state) throws Exception {
		   switch (state) {
		   case READ_LENGTH:
			   length = buf.readInt();
			   if (length > Config.DATA_LENGTH_MAX) {
				   channel.close();
				   return null;
			   }
			   checkpoint(MyDecoderState.READ_CONTENT);
		   case READ_CONTENT:
			   ChannelBuffer frame = buf.readBytes(length);
			   checkpoint(MyDecoderState.READ_LENGTH);
			   return frame;
		   default:
			   throw new Error("Shouldn't reach here.");
		   }
	   }
}


